// 获取cookie，判断是否有cookie，如果没有就跳转到登录界面
let username = getCookie()
if (!username.login) {
    location.href = './login.html';
}
let url = location.href
let userId = location.search.slice(location.search.indexOf('?') + 1) * 1
// 点击返回回退一个页面
$('h1 a').on('click', function (e) {
    e.preventDefault();
    history.back()
})
// 1.input file 上传标签绑定change事件
function img() {

    let
        fileInput = document.getElementById('test-image-file'),
        info = document.getElementById('test-file-info'),
        preview = document.getElementById('test-image-preview');
    // 监听change事件:
    fileInput.addEventListener('change', function () {
        // 清除背景图片:
        preview.style.backgroundImage = '';
        // 检查文件是否选择:
        if (!fileInput.value) {
            info.innerHTML = '没有选择文件';
            return;
        }
        // 获取File引用:
        let file = fileInput.files[0];
        // 获取File信息:
        // info.innerHTML = '文件: ' + file.name + '<br>' +
        //     '大小: ' + file.size + '<br>' +
        //     '修改: ' + file.lastModifiedDate;
        if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif'&& file.type !== 'image/webp') {
            alert('不是有效的图片文件!');
            return;
        }
        // 读取文件:
        let reader = new FileReader();
        reader.onload = function (e) {
            let data = e.target.result; // '...(base64编码)...'   
            preview.style.backgroundImage = 'url(' + data + ')';
            // let Imgurl = $('#test-image-preview').css('backgroundImage')


            $.post(
                "/ap/addInformationImg.php", {
                    userId: userId,
                    userImg: data

                },
                function (res) {
                    //   console.log(res);
                },
                "json"
            );
            
        };
        
        // 以DataURL的形式读取文件:
        reader.readAsDataURL(file);
    });
    userT()
}
// userT()
// 获取该页面的网址拿到网址上的用户名

function userT() {
    $.ajax({
        url: '/ap/getInformationImg.php',
        method: "post",
        data: {
            userId: userId,
            

        },
        
        success(r) {
              
              let res=JSON.parse(r)
            //   console.log($('#test-image-preview'));
              $('#test-image-preview').css({backgroundImage:`url(${res[0].userimg})`})
              
            //   res.map(function(item){
            //       console.log(item.userimg);
            //       return $('#test-image-preview').css({backgroundImage:`url(${item.userimg})`})
            //   })
              

            
        }
    })
}
AA();
// 把用户名传递给后端，拿到数据库中student表对应该用户的数据
function AA() {

    $.ajax({
        url: '/ap/getstudent.php',
        method: "post",
        data: {
            userId: userId
        },
        dataType: 'json',
        success(res) {
            //   console.log(res);

            $.rander(res)
            $.wanshan(res)

            $.pass()
            img()

        }
    })
}

aj()
// 把用户名传递给后端，拿到数据库中information表对应该用户的数据
function aj() {
    $.ajax({
        url: '/ap/getInformation.php',
        method: "post",
        data: {
            userId: userId
        },
        dataType: 'json',
        success(res) {
            //   console.log(res);
            res.map(function (item) {
                if (item.userId) {
                    $.rander1(res)
                    $.wanshan2(res)
                    $.pass()
                    img()

                }
                return

            })

        }
    })

}

// 点击修改密码时设置学号为该登录的用户名
$.extend({

    pass: function () {
        $('.updataPass').on('click', function () {
            $('.password').css({
                display: "block"
            })
            $('#ID').val(userId)

        })
    }
})
$.extend({
    // 将后端传过来的数据进行渲染
    rander: function (data) {

        let res = data.map(function (item) {

            return `<div class="touxiang" id="test-image-preview"style="border: 1px solid rgb(204, 204, 204); width: 100px; height: 100px; background-size: contain; background-repeat: no-repeat; background-position: center center;">
            
            <p class="bianji"><input class="hide" type="file" id="test-image-file"><span>编辑头像</span></p>
        </div>
                    <div class="name">
                        <label for="">姓名：</label> ${item.s_name}</div>
                    <div class="userId">
                        <label for="">学号：</label> ${item.s_id}</div>
                    <div class="sex"><label for="">性别：</label>${item.s_sex}</div>
                    <div class="nation"><label for="">民族：</label></div>
                    <div class="school"><label for="">就读院校：</label></div>
                    <div class="college"><label for="">二级学院：</label></div>
                    <div class="class"><label for="">所在班级：</label>${item.banji}</div>
                    <div class="major"><label for="">专业：</label></div>
                    <div class="Enrollment"><label for="">入学年份：</label>2018年9月</div>
                
                    <div class="system"><label for="">学制：</label></div>
                    <div class="education"><label for="">学历：</label></div>
                    <div class="btn"><button class="ziliao">完善资料</button>
                        <button class="updataPass">修改密码</button>
                    </div>`
        })
        $('.container').html(res)

    },
    rander1: function (data) {

        let res = data.map(function (item) {

            return `<div class="touxiang" id="test-image-preview"style="border: 1px solid rgb(204, 204, 204); width: 100px; height: 100px; background-size: contain; background-repeat: no-repeat; background-position: center center;">
           
            <p class="bianji"><input class="hide" type="file" id="test-image-file"><span>编辑头像</span></p>
        </div>
                  <div class="name">
                      <label for="">姓名：</label> ${item.username}</div>
                  <div class="userId">
                      <label for="">学号：</label> ${item.userId}</div>
                  <div class="sex"><label for="">性别：</label>${item.sex}</div>
                  <div class="nation"><label for="">民族：</label>${item.nation}</div>
                  <div class="school"><label for="">就读院校：</label>${item.school}</div>
                  <div class="college"><label for="">二级学院：</label>${item.college}</div>
                  <div class="class"><label for="">所在班级：</label>${item.class}</div>
                  <div class="major"><label for="">专业：</label>${item.major}</div>
                  <div class="Enrollment"><label for="">入学年份：</label>${item.Enrollment}</div>
              
                  <div class="system"><label for="">学制：</label>${item.system}</div>
                  <div class="education"><label for="">学历：</label>${item.education}</div>
                  <div class="btn"><button class="ziliao">完善资料</button>
                      <button class="updataPass">修改密码</button>
                  </div>`
        })
        $('.container').html(res)


    }
})

$.extend({
    wanshan: function (data) {
        $('.ziliao').on('click', function () {
            $('.updata').css({
                display: "block"
            })
            //   console.log(data);
            let res = data.map(function (item) {

                return `
                        <p><label for="">姓名：</label><input id="username" type="text" value="${item.s_name}"></p>
                        <p><label for="">学号：</label><input id="userId" type="text" value="${item.s_id}"></p>
                        <p><label for="">性别：</label><input id="sex" type="text" value="${item.s_sex}"></p>
                        <p><label for="">民族：</label><input id="nation" type="text"></p>
                        <p><label for="">就读院校：</label><input id="school" type="text"></p>
                        <p><label for="">二级学院：</label><input id="college" type="text"></p>
                        <p><label for="">所在班级：</label><input id="class" type="text" value="${item.banji}"></p>
                        <p><label for="">专业：</label><input id="major" type="textr"></p>
                        <p><label for="">入学年份：</label><input id="Enrollment"  type="text"></p>
                        <p><label for="">学制：</label><input id="system" type="text"></p>
                        <p><label for="">学历：</label><input id="education" type="text"></p>`
            }).join('')
            // console.log(res);

            $('.conTent h1').after(res)


        })

        //   $('.updataPass').on('click', function () {
        //       $('.password').css({
        //           display: "block"
        //       })
        //   })
    },
    wanshan2: function (data) {
        $('.ziliao').on('click', function () {
            $('.updata').css({
                display: "block"
            })
            //   console.log(data);
            let res = data.map(function (item) {

                return `
                      <p><label for="">姓名：</label><input id="username" type="text" value="${item.username}"></p>
                      <p><label for="">学号：</label><input id="userId" type="text" value="${item.userId}"></p>
                      <p><label for="">性别：</label><input id="sex" type="text" value="${item.sex}"></p>
                      <p><label for="">民族：</label><input id="nation" type="text" value="${item.nation}"></p>
                      <p><label for="">就读院校：</label><input id="school" type="text" value='${item.school}'></p>
                      <p><label for="">二级学院：</label><input id="college" type="text" value='${item.college}'></p>
                      <p><label for="">所在班级：</label><input id="class" type="text" value="${item.class}"></p>
                      <p><label for="">专业：</label><input id="major" type="textr" value="${item.major}"></p>
                      <p><label for="">入学年份：</label><input id="Enrollment"  type="text" value="${item.Enrollment}"></p>
                      <p><label for="">学制：</label><input id="system" type="text" value="${item.system}"></p>
                      <p><label for="">学历：</label><input id="education" type="text" value="${item.education}"></p>`
            }).join('')
            // console.log(res);
            $('.conTent h1').after(res)


        })
        //   console.log(userId);
        // $('.updataPass').on('click', function () {
        //     $('.password').css({
        //         display: "block"
        //     })
        //     $('#ID').val(userId)

        // })
    }


})

// 填写好资料后点击提交，把数据传给后端
$('.button').on('click', function () {
    $('.updata').css({
        display: 'none'
    })
    let userId = $('#userId').val() * 1;

    $.post(
        "/ap/addInfomation.php", {
            username: $('#username').val(),
            userId: userId,
            // userImg: 'img',
            sex: $('#sex').val(),
            nation: $('#nation').val(),
            school: $('#school').val(),
            college: $('#college').val(),
            class: $('#class').val(),
            major: $('#major').val(),
            Enrollment: $('#Enrollment').val(),
            system: $('#system').val(),
            education: $('#education').val(),

        },
        function (res) {
            //   console.log(res);
        },
        "json"
    );

    //   $.ajax({
    //       url: "/ap/addInfomation.php",
    //       mathod: 'post',
    //       data: {
    //           username: $('#username').val(),
    //           userId: userId,
    //           userImg: result,
    //           sex: $('#sex').val(),
    //           nation: $('#nation').val(),
    //           school: $('#school').val(),
    //           college: $('#college').val(),
    //           class: $('#class').val(),
    //           major: $('#major').val(),
    //           Enrollment: $('#Enrollment').val(),
    //           system: $('#system').val(),
    //           education: $('#education').val(),

    //       },
    //       dataType: 'json',
    //       async: false,
    //       success: function (res) {
    //           console.log(res);
    //       },
    //       error: function (err) {
    //           console.log(err);
    //       }
    //   })
    aj();
})
// 点击取消隐藏填写资料区域
$('.quxiao').on('click', function () {
    $('.updata').css({
        display: 'none'
    }).children('.conTent').children('p').remove()

})
// 修改密码
$.extend({
    updataPass: function () {
        $('#password').on('focus', function () {
            $('.tishi').css({
                display: 'block'
            })
            $('.erro').css({
                display: 'none'
            })
        })
        $('#password').on('blur', function () {
            $('.tishi').css({
                display: 'none'
            })
        })
        $('.BTN').on('click', function () {
            //   console.log(userId);
            // 正则判断修改的密码是否符合设定的规则
            let reg = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?![,\.;:\?]+$)[0-9a-zA-Z,\.;:\?]{6,14}$/;
            if (!(reg.test($('#password').val()))) {

                $('.erro').css({
                    display: 'block'
                })
                return
            }

            // 确认修改后将修改的密码传递给后端
            $.post(
                "/ap/updataPass.php", {
                    sid: userId,
                    password: $('#password').val()
                },
                function (res) {
                    // console.log(res);
                    //   $.loginAgain(res)
                },
                "json"
            );
            //   console.log(getCookie());
            // 确认修改后删除当前的cookie，跳转到登录界面重新登录系统
            Cookies.remove('login')
            let login = getCookie()

            if (!login.login) {
                location.href = './login.html';
            }
        })
        // 点击取消隐藏修改密码
        $('.qux').on('click', function () {
            $('.password').css({
                display: 'none'
            })
        })
    }

})
$.updataPass()
//   $.extend({
//       loginAgain: function (res) {
//           if (res) {
//               console.log(1);
//           }
//       }
//   })